"""用户账户相关功能：注册、短信、登录、注销"""
import uuid,datetime

from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse


def login(request):
    """用户名密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request,data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        from django.db.models import Q
        user_object = models.UserInfo.objects.filter(Q(username=username)|Q(email=username)|Q(mobile_phone=username)).filter(password=password).first()
        if user_object:
            # 用户名密码正确
            # 用户信息放入session
            request.session['user_id'] = user_object.id
            request.session['user_name'] = user_object.username
            # 设置登录超时
            request.session.set_expiry(60*64*24*14)
            return redirect('index')
        form.add_error('username', '用户名或者密码不正确')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    from utils.image_code import check_code
    #生成图片验证码
    image_object, code = check_code()
    request.session['image_code'] = code
    #设置超时
    request.session.set_expiry(600)
    # 将图片写入内存
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def login_sms(request):
    """短息登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)

    if form.is_valid():
        # 用户输入正确，登陆成功
        user_object = form.cleaned_data.get('mobile_phone')
        # 用户信息放入session
        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username
        # print(user_object,user_object.id,user_object.username,user_object.email)
        request.session.set_expiry(60 * 64 * 24 * 14)
        return JsonResponse({"status": True, "data": "/index/"})
    return JsonResponse({'status': False, 'error': form.errors})


def register(request):
    """ 注册  """
    # 如果是get请求，则显示页面
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    # 如果是POST请求，则走注册流程
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过后，将表单写入数据库，密码需要密文传输
        instance = form.save()  # 提交时会剔除没有字段的数据
        """以下代码对应中间件方式一，如采用方式二需注释掉下面代码"""
        # 获取免费版价格策略
        policy_object = models.PricePolicy.objects.filter(category=1,title="个人免费版").first()
        #创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()), #随机字符串
            user=instance,
            price_policy=policy_object, # 免费版
            count= 0, # 数量(年)：无限期
            price=0, # 实际支付价格
            start_datetime=datetime.datetime.now(),
            end_datetime= "2031-08-25 21:29:51.000000",
        )
        # print(instance)
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})

def logout(request):
    request.session.flush()
    return redirect('index')

def send_sms(request):
    """  发送短信  """
    form = SendSmsForm(request, data=request.GET)
    # mobile_phone = None
    # if form.is_valid():
    #     mobile_phone = form.cleaned_data.get('mobile_phone')
    # from django_redis import get_redis_connection
    # conn = get_redis_connection()
    # try:
    #     redis_code = conn.get(mobile_phone)
    #     # print('redis_code:%s'%redis_code)
    # except:
    #     return JsonResponse({'status': False, 'error': form.errors})
    # print(request.GET)
    # print(form.errors)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


import random
from utils.tencent.sms import send_sms_single
from django.conf import settings

# def send_sms(request):
#     """ 发送短信
#         ?tpl=login -> 645736
#         ?tpl=register -> 645735
#     """
#     tpl = request.GET.get('tpl')
#     template_id = settings.TENCENT_SMS_TEMPLATES.get(tpl)
#
#     if not template_id:
#         return HttpResponse('模板不存在')
#
#     code = random.randrange(1000, 9999)
#     res = send_sms_single('15773154328', template_id, [code, ])
#     if res['result'] == 0:
#         return HttpResponse('成功')
#     else:
#         return HttpResponse(res['errmsg'])
